<?php
/**
 * Created by PhpStorm
 * User: whh
 * Date: 2023/8/8
 * Time: 23:16
 */

namespace app\backstage\logic;


use app\common\model\Banner;
use app\common\model\DefaultBookshelf;
use app\common\model\Novel;
use app\common\model\QuickApp;
use app\common\model\TaskConfig;
use app\common\model\Recommend;
use app\common\model\RecommendNovel;
use app\common\model\SignConfig;
use think\Db;
use think\db\Expression;

class WebsiteLogic
{

    /**
     * 获取默认书架
     * @param $where
     * @param $page
     * @param $limit
     * @return \think\response\Json
     * @Author: whh
     */
    public function getBookshelfNovels($where, $page, $limit)
    {
        $agent_id = input('agent_id');
        $user = request()->_user;
        $agents = getAgents();
        $agents_id = array_column($agents,'id');
        if ($agent_id > 0  && !in_array($agent_id, $agents_id)) {
            return errJson('无此代理商权限');
        }
        $type = input('type');
        if ($type != '') {
            $cWhere[] = ['type', '=', $type];
        }
        $cWhere[] = ['agent_id', '=', $agent_id];

        $orderBy = "id desc";
        $configSet = DefaultBookshelf::where($cWhere)->field("id,novel_id")->order($orderBy)->select()->toArray();
        $novelIds = array_column($configSet, 'novel_id');
        $configSet = array_column($configSet, null, 'novel_id');
        $where[] = ['id', 'in', $novelIds];
        $order = "id asc";
        if ($novelIds) {
            $order = new Expression('field(id,' . implode(',', $novelIds) . ')');
        }
        $field = "id,title,freq_id,class_id,scale,in_shelf,cover";
        $list = Novel::getList($where, $field, $order, $page, $limit, ['freq', 'novel_class']);
        foreach ($list as $k => $v) {
            $list[$k]['source_id'] = $configSet[$v['id']]['id'];
        }
        $count = Novel::getCount($where);
        return sucJson($list, $count);
    }

    /**
     * 添加默认书架
     * @param $agent_id
     * @param $nIds
     * @return \think\response\Json
     * @throws \Exception
     */
    public function addBookshelfNovelIds($agent_id, $nIds)
    {
        $user = request()->_user;
        $agents = getAgents();
        $agents_id = array_column($agents,'id');
        if ($agent_id > 0  && !in_array($agent_id, $agents_id)) {
            return errJson('无此代理商权限');
        }

        $nIds = array_filter(explode(',', $nIds));
        $nIds = array_unique($nIds);

        $type = input('type', 1);
        $cWhere[] = ['type', '=', $type];
        $cWhere[] = ['agent_id', '=', $agent_id];
        $haveNIds = DefaultBookshelf::where($cWhere)->column('novel_id');
        $diff = array_diff($nIds, $haveNIds);//得到没有的值
        $novelModel = new Novel();
        $saveIds = $novelModel->where("id", "in", $diff)->column('id');
        if (in_array($type, [0, 2])) {
            $notIds = Novel::where('id', 'in', $saveIds)->where('scale', '<>', 'C')->column('id');
            if ($notIds) {
                return errJson('添加失败，屏蔽地区不能设置非C级书，书id:' . implode(',', $notIds));
            }
        }
        $count = count($saveIds);
        $saveArr = [];
        foreach ($saveIds as $id) {
            $saveArr[] = [
                'agent_id' => $agent_id,
                'novel_id' => $id,
                'type' => $type
            ];
        }
        $model = new DefaultBookshelf();
        $model->saveAll($saveArr);
        if ($count > 0) {
            return sucJson("成功添加{$count}本");
        } else {
            return errJson("小说不存在或已添加");
        }
    }

    /**
     * 删除书籍
     * @param $quickId
     * @param $type
     * @param $novelIds
     * @return \think\response\Json
     * @throws \Exception
     */
    public function delBookshelfNovel($quickId, $type, $novelIds)
    {
        $where[] = ['quick_id', '=', $quickId];
        $where[] = ['novel_id', 'in', $novelIds];
        $where[] = ['type', '=', $type];
        DefaultBookshelf::where($where)->delete();
        return sucJson();
    }

    /**
     * 设置签到书点
     * @param $quickId
     * @param $index
     * @param $point
     * @return \think\response\Json
     * @Author: whh
     */
    public function setSignPoint($quickId, $index, $point)
    {
        $role = request()->_role;
        $user = request()->_user;
        $quick = \app\common\model\QuickApp::get($quickId);
        if (!$quick) {
            return errJson('App不存在');
        }

        if($role->alias == 'agent')
        {
            $myQIds = Db::table('quick_app_mp_manager')->where('uid',$user->id)->column('quick_id');
            if(empty($myQIds))
            {
                return errJson('无此App权限');
            }
            if (!in_array($quickId, $myQIds)) {
                return errJson('无此App权限');
            }
        }

        if ($role->alias == 'agent') {
            $manage_id = $user->id;
        } else {
            $manage_id = 0;
        }

        $where[] = ['quick_id', '=', $quickId];
        $where[] = ['manage_id', '=', $manage_id];
        $defaultTemplate = SignConfig::defaultTemplate($quick->info->sign_max);
        $mySignData = SignConfig::where($where)->value('sign_data');
        if ($mySignData) {
            $mySignData = json_decode($mySignData, true);
        }
        $data = [];
        foreach ($defaultTemplate as $k => $v) {
            if (isset($mySignData[$k])) {
                $data[$k] = $mySignData[$k];
            } else {
                $data[$k] = $v;
            }
            if ($k == $index) {
                $data[$k]['point'] = intval($point);
            }
        }
        $data = json_encode($data);
        if ($mySignData) {
            SignConfig::where($where)->setField('sign_data', $data);
        } else {
            SignConfig::insert([
                'manage_id' => $manage_id,
                'quick_id' => $quickId,
                'sign_data' => $data
            ]);
        }
        return sucJson();
    }


    /**
     * 推荐位列表
     * @param $where
     * @param $page
     * @param $limit
     * @return \think\response\Json
     * @Author: whh
     */
    public function recommendList($where, $page, $limit)
    {
        $field = "*";
        $orderBy = "id desc";
        $list = Recommend::getList($where, $field, $orderBy, $page, $limit, ['managerUser']);
        foreach ($list as $k => $model) {
            $list[$k]['pb_novel_count'] = RecommendNovel::where("rid", $model->id)->where("type", 2)->count();
            $list[$k]['xs_novel_count'] = RecommendNovel::where("rid", $model->id)->where("type", 1)->count();
        }
        $count = Recommend::getCount($where);
        return sucJson($list, $count);
    }


    /**
     * 设置推荐位
     * @param $data
     * @return \think\response\Json
     * @Author: whh
     */
    public function setRecommend($data)
    {
        $recomId = isset($data['id']) && $data['id'] ? $data['id'] : 0;

        $where[] = ['title', '=', $data['title']];
        $where[] = ['freq', '=', $data['freq']];
        $where[] = ['agent_id', '=', $data['agent_id']];
        $have = Recommend::where($where)->find();
        if (!$recomId) {
            if ($have) {
                return errJson('此App同频道下推荐位（标题）已存在');
            }
            $model = new Recommend();
            $data['location_key'] = $this->make_token();
            $model->allowField(true)->save($data);
            return sucJson();
        } else {
            $model = Recommend::get($recomId);
            if (!$model) {
                return errJson('推荐位不存在');
            }
            if ($have && $have['id'] != $recomId) {
                return errJson('修改失败，此App同频道下已有相同的推荐位');
            }
            $model->allowField(['agent_id', 'title', 'en_title', 'freq', 'desc'])->save($data);
            return sucJson();
        }
    }


    /**
     * 制作Token
     * @return string
     */
    public function make_token()
    {
        $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $rand = $code[rand(0, 25)]
            . strtoupper(dechex(date('m')))
            . date('d') . substr(time(), -5)
            . substr(microtime(), 2, 5)
            . sprintf('%02d', rand(0, 99));
        for (
            $a = md5($rand, true),
            $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
            $d = '',
            $f = 0;
            $f < 8;
            $g = ord($a[$f]),
            $d .= $s[($g ^ ord($a[$f + 8])) - $g & 0x1F],
            $f++
        ) ;
        return $d;
    }

    /**
     * 删除推荐位
     * @param $ids
     * @return \think\response\Json
     * @throws \Exception
     * @Author: whh
     */
    public function delRecommend($ids)
    {
        foreach ($ids as $id) {
            $model = Recommend::get($id, 'novels');
            if ($model) {
                $model->together('novels')->delete();
            }
        }
        return sucJson();
    }

    /**
     * 删除banner
     * @param $ids
     * @return \think\response\Json
     * @throws \Exception
     */
    public function delBanner($ids)
    {
        foreach ($ids as $id) {
            $model = Banner::get($id);
            if ($model) {
                $model->delete();
            }
        }
        return sucJson();
    }


    /**
     * 推荐位书籍列表
     * @param $where
     * @param $page
     * @param $limit
     * @return \think\response\Json
     * @Author: whh
     */
    public function recommendNovel($where, $page, $limit)
    {
        $field = '*';
        $orderBy = "sort asc,id desc";
        $list = RecommendNovel::getList($where, $field, $orderBy, $page, $limit, ['novel']);
        foreach ($list as $k => $v) {
            $v->novel->freq;
            $v->novel->novel_class;
        }
        $count = RecommendNovel::getCount($where);
        return sucJson($list, $count);
    }

    /**
     * 添加推荐位小说
     * @param $rid
     * @param $type
     * @param $nIds
     * @return \think\response\Json
     * @throws \Exception
     */
    public function addRecommendNovel($rid, $type, $nIds)
    {
        $recommend = Recommend::get($rid);
        if (!$recommend) {
            return errJson('推荐位不存在');
        }
        $nIds = explode(',', $nIds);
        $nIds = array_unique($nIds);
        $haveNIds = RecommendNovel::where('rid', $rid)->where('type', $type)->column('novel_id');
        $haveCount = count($haveNIds);
        if ($haveCount >= 100) {
            return sucJson("成功添加0本");
        }
        $diff = array_diff($nIds, $haveNIds);//得到没有的值
        $novelModel = new Novel();
        $saveIds = $novelModel->where("id", "in", $diff)->column('id');
        $length = 100 - $haveCount;
        if ($length) {
            $saveIds = array_slice($saveIds, 0, $length);
        }
        $count = count($saveIds);
        $saveArr = [];
        foreach ($saveIds as $id) {
            $saveArr[] = [
                'rid' => $rid,
                'novel_id' => $id,
                'type' => $type,
            ];
        }
        $model = new RecommendNovel();
        $model->saveAll($saveArr);
        if ($count > 0) {
            return sucJson("成功添加{$count}本");
        } else {
            return errJson("小说不存在或已添加");
        }
    }


    public function plAddRecommendNovels($params)
    {
        $addType = $params['add_type'];
        $freqIds = $params['freq_ids'];
        $nIds = $params['nIds'];
        $nIds = explode(',', $nIds);
        $nIds = array_unique($nIds);
        $qaIdArr = $params['quick_apps'];
        $titleArr = $params['recommend_titles'];
        $novelType = $params['novel_type'];
        $novelModel = new Novel();

        $rWhere[] = ['title', 'in', $titleArr];
        $rWhere[] = ['freq', 'in', $freqIds];
        $rWhere[] = ['agent_id', 'in', $qaIdArr];
        $rIds = Recommend::where($rWhere)->column('id');
        $saveArr = [];
        if ($addType == 1) {
            //覆盖
            $saveIds = $novelModel->where("id", "in", $nIds)->column('id');
            $saveIds = array_slice($saveIds, 0, 100);
            RecommendNovel::where("rid", 'in', $rIds)->where('type', $novelType)->delete();
            foreach ($rIds as $rId) {
                foreach ($saveIds as $id) {
                    $saveArr[] = [
                        'rid' => $rId,
                        'novel_id' => $id,
                        'type' => $novelType,
                    ];
                }
            }
        } else {
            //新增加
            foreach ($rIds as $rid) {
                $haveNIds = RecommendNovel::where('rid', $rid)->where('type', $novelType)->column('novel_id');
                $haveCount = count($haveNIds);
                if ($haveCount >= 100) {
                    continue;
                }
                $diff = array_diff($nIds, $haveNIds);//得到没有的值
                $saveIds = $novelModel->where("id", "in", $diff)->column('id');
                $length = 100 - $haveCount;
                if ($length) {
                    $saveIds = array_slice($saveIds, 0, $length);
                }
                foreach ($saveIds as $id) {
                    $saveArr[] = [
                        'rid' => $rid,
                        'novel_id' => $id,
                        'type' => $novelType,
                    ];
                }
            }
        }
        $model = new RecommendNovel();
        $model->saveAll($saveArr);
        return sucJson();
    }

    /**
     * banner列表
     * @param $where
     * @param $page
     * @param $limit
     * @return \think\response\Json
     */
    public function bannerList($where, $page, $limit)
    {
        $field = "*";
        $orderBy = "id desc";
        $list = Banner::getList($where, $field, $orderBy, $page, $limit, ['managerUser', 'novel', 'activity']);
        $count = Banner::getCount($where);
        return sucJson($list, $count);
    }


    /**
     * 设置banner
     * @param $data
     * @return \think\response\Json
     * @Author: whh
     */
    public function setBanner($data)
    {
        $quickId = explode(',',$data['quick_id']);

        $params = $data;

        $msg = '';
        foreach ($quickId as $v)
        {
            $params['quick_id'] = $v;
            $result = $this->setBannerByQuick($params);
            if($result['code'] != 100)
            {
                $msg .= $result['msg'].'<br />';
            }
        }

        if(strlen($msg) > 1)
        {
            return errJson($msg);
        }

        return sucJson();
    }

    /*处理单个Appbanner设置*/
    private function setBannerByQuick($data)
    {
        $id = isset($data['id']) && $data['id'] ? $data['id'] : 0;
        $qa = QuickApp::get($data['quick_id']);

        if (!$qa) {
            return ['code'=>102,'msg'=>'App【'.$qa['name'].'】不存在'];
        }
        $where[] = ['seat', '=', $data['seat']];
        $where[] = ['quick_id', '=', $data['quick_id']];
        $where[] = ['type', '=', $data['type']];
        $where[] = ['activity_id', '=', $data['activity_id']];
        $where[] = ['content_type', '=', 2];

        $data['content_type'] = 2;
        $typeStr = '活动';
        $have = Banner::where($where)->find();
        if (!$id) {
            if ($have) {
                return ['code'=>102,'msg'=>'添加失败，此App【'.$qa['name'].'】下读者类型 + 页面位置存在相同' . $typeStr];
            }
            $model = new Banner();
            $model->allowField(true)->save($data);
            return ['code'=>100,'msg'=>'操作成功'];
        } else {
            $model = Banner::get($id);
            if (!$model) {
                return ['code'=>102,'msg'=>'此banner对象不存在'];
            }
            if ($have && $have['id'] != $id) {
                return ['code'=>102,'msg'=>'修改失败，此App【'.$qa['name'].'】下读者类型 + 页面位置已有相同' . $typeStr];
            }
            $model->allowField(['quick_id', 'seat', 'type', 'content_type', 'novel_id', 'activity_id', 'banner'])->save($data);
            return ['code'=>100,'msg'=>'操作成功'];
        }
    }

    /**
     * 获取任务
     * @param $quickId
     * @return array|array[]
     * @Author: whh
     */
    public function getTaskData($quickId)
    {
        $user = request()->_user;
        $role = request()->_role;
        if ($role->alias == 'agent') {
            $manage_id = $user->id;
        } else {
            $manage_id = 0;
        }
        $where[] = ['quick_id', '=', $quickId];
        $where[] = ['manage_id', '=', $manage_id];
        $defaultTemplate = TaskConfig::defaultTemplate($quickId);
        $myTaskData = TaskConfig::where($where)->value('task_data');
        $myTaskData = json_decode($myTaskData, true);
        $data = [];
        if ($myTaskData) {
            foreach ($defaultTemplate as $k => $v) {
                if (isset($myTaskData[$k])) {
                    $data[$k] = $myTaskData[$k];
                } else {
                    $data[$k] = $v;
                }
            }
        } else {
            $data = $defaultTemplate;
        }
        return $data;
    }


    /**
     * 设置上下架
     * @Author: whh
     */
    public function setTaskDisplay()
    {
        $quick_id = input('quick_id');
        $key = input('key');
        $display = input('display');
        $role = request()->_role;
        $user = request()->_user;
        if ($role->alias == 'agent') {
            $manage_id = $user->id;
        } else {
            $manage_id = 0;
        }
        $where[] = ['quick_id', '=', $quick_id];
        $where[] = ['manage_id', '=', $manage_id];
        $myTaskData = TaskConfig::where($where)->value('task_data');
        $data = $this->getTaskData($quick_id);
        foreach ($data as $k => $v) {
            if ($k == $key) {
                $data[$k]['display'] = $display;
            }
        }
        $task_data = json_encode($data, JSON_UNESCAPED_UNICODE);
        if (!$myTaskData) {
            TaskConfig::insert([
                'quick_id' => $quick_id,
                'manage_id' => $manage_id,
                'task_data' => $task_data,
            ]);
        } else {
            TaskConfig::where($where)->setField('task_data', $task_data);
        }
    }


    /**
     * 设置任务
     * @Author: whh
     */
    public function setTask()
    {
        $params = request()->param();
        $quick_id = input('quick_id');
        $key = input('key');
        $user = request()->_user;
        if ($user->role->alias == 'agent') {
            $manage_id = $user->id;
        } else {
            $manage_id = 0;
        }
        $where[] = ['quick_id', '=', $quick_id];
        $where[] = ['manage_id', '=', $manage_id];
        $myTaskData = TaskConfig::where($where)->value('task_data');
        $data = $this->getTaskData($quick_id);
        foreach ($data as $k => $v) {
            if ($k == $key) {
                $data[$k]['title'] = $params['title'];
                $data[$k]['desc'] = $params['desc'];
                $data[$k]['point'] = intval($params['point']);
                $data[$k]['sort'] = intval($params['sort']);
                if ($k == 'read') {
                    $data[$k]['chapter_num'] = intval($params['chapter_num']);
                } elseif ($k == 'calendar') {
                    $data[$k]['event']['title'] = $params['eTitle'];
                    $data[$k]['event']['description'] = $params['description'];
                    $data[$k]['event']['startDate'] = $params['startDate'];
                    $data[$k]['event']['endDate'] = $params['endDate'];
                    $data[$k]['event']['rrule'] = $params['rrule'];
                    $data[$k]['event']['remindMinutes'] = $params['remindMinutes'];
                }
            }
        }
        $task_data = json_encode($data, JSON_UNESCAPED_UNICODE);
        if (!$myTaskData) {
            TaskConfig::insert([
                'quick_id' => $quick_id,
                'manage_id' => $manage_id,
                'task_data' => $task_data,
            ]);
        } else {
            TaskConfig::where($where)->setField('task_data', $task_data);
        }
    }
}